/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utiles.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author fcarou
 */
public class Parser
{
    public List parseArray (JSONArray array, Class clazz)
    {
        if (array == null)
            return null;
        
        if (array.length() == 0)
            return new ArrayList<>();
        
        List lista = new ArrayList<>();
        
        for (int i = 0; i < array.length(); i++)
            lista.add(parseObject(array.getJSONObject(i), clazz));
        
        return lista;
    }
    
    public Object parseObject (JSONObject object, Type clazz)
    {
        GsonBuilder b = new GsonBuilder();
        b.registerTypeAdapter(Calendar.class, new CalendarSerializer());
        Gson gson = b.create();
        
        return gson.fromJson(object.toString(), clazz);
    }
    
    public Object parseObject (String object, Class clazz)
    {
        GsonBuilder b = new GsonBuilder();
        b.registerTypeAdapter(Calendar.class, new CalendarSerializer());
        Gson gson = b.create();
        
        return gson.fromJson(object, clazz);
    }
    
    public String toJson (Object object)
    {
        return getGson().toJson(object);
    }
    
    public Gson getGson ()
    {
        GsonBuilder b = new GsonBuilder();
        b.registerTypeAdapter(GregorianCalendar.class, new CalendarSerializer());
        
        return b.create();
    }
}
